package com.zrb.mobile.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListAdapter;
import android.widget.AbsListView.OnScrollListener;

import com.hhpm.lib.swipelistview.SwipeMenuListView;
import com.zrb.mobile.R;
 

public class SwipeMenuListViewEx  extends SwipeMenuListView implements OnScrollListener{
	
	  int pagesize=10;
	ListAdapter mBaseAdapter;	
	View mloadingview; 
	boolean isLoading=false;
	onLoadMoreListener monLoadMoreListener;
	private boolean mLastItemVisible;
	boolean canloadmore=true;
	public SwipeMenuListViewEx(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}
 
	public SwipeMenuListViewEx(Context context, AttributeSet attrs, int defStyle) {
	        super(context, attrs, defStyle);
	       // init();
	}

    public SwipeMenuListViewEx(Context context, AttributeSet attrs) {
	        super(context, attrs);
	       // init();
	 }
 
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		if (null != monLoadMoreListener) {
			mLastItemVisible = (totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount - 1);
		}
	}



	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub
		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && null != monLoadMoreListener && mLastItemVisible) {
			//mOnLastItemVisibleListener.onLastItemVisible();
			 onLastItemVisible();
		}
	}
  
	public void setPagesize(int curPagesize){
		pagesize=curPagesize;
	}

	public void initAdapter(ListAdapter madapter){
		mBaseAdapter=madapter;
		this.setAdapter(madapter);
	}
 	
	public void setOnLoadMoreListener(onLoadMoreListener onLoadMoreListener){
		
		LayoutInflater inflater = LayoutInflater.from(this.getContext());
		mloadingview = inflater.inflate(R.layout.ss_new_comment_footer, null);
 		 
		this.addFooterView(mloadingview);///.addFooterView();
		mloadingview.setVisibility(View.GONE);
	    setOnScrollListener(this);

		monLoadMoreListener=onLoadMoreListener;
		//initOnLastItemVisibleListener();
	}
	
	private void onLastItemVisible(){
		
		    if(!canloadmore) return;
	    	if(mBaseAdapter.getCount()<pagesize) return;
			if(isLoading) return;

			isLoading=true;
			mloadingview.setVisibility(View.VISIBLE);
			if(monLoadMoreListener!=null) monLoadMoreListener.OnLoadMoreEvent();
	}
	
	public void hideloading(){
		isLoading=false;
		mloadingview.setVisibility(View.GONE);
	}
	
	public void checkloadMore(int size){
 		if(size<pagesize) canloadmore=false;;
	}
	
	public void setCanloadMore(){
		canloadmore=true;;
	}
}
